
package com.hlkj.pay.app.merchant.ext.impl.gtzfpay.ext;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.GtzfScenePayOrderExtPt;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.constant.GtzfPayConstant;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.constant.GtzfPayExtConstant;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.dto.GtzfPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.dto.GtzfpayAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.utils.GtzfPayRsaUtil;
import com.hlkj.pay.app.merchant.ext.impl.gtzfpay.utils.HttpUtils;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.util.MerchantUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 主扫统一下单 用户扫支付码
 *
 * @author HlpayTeam
 * @date 2024/11/18 13:07
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = GtzfPayExtConstant.MINI_APP)
public class GtzfPayMiniOrderExtPt extends GtzfPaySceneCommonPayOrder implements GtzfScenePayOrderExtPt {

    @Value("${hlkj.domain}")
    private String domain;

    @Override
    public void submitChannelPayOrder(ChannelPayOrderContext channelPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        GtzfPayConfig config = JsonUtils.parseObject(channelConfig, GtzfPayConfig.class);
        PayOrderDO payOrderDO = channelPayOrderContext.getPayOrderDO();
        MerchantAppChannelDO merchantAppChannelDO = channelPayOrderContext.getMerchantAppChannelDO();

        try {

            //国通需回调地址要替换成映射地址
            channelPayOrderContext.setNotifyUrl(channelPayOrderContext.getNotifyUrl().replace(domain, config.getCallbackDomain()));
            GtzfpayAppChannelParams appChannelParams = easyPayAppChannelParams(merchantAppChannelDO, config);

            Map<String, String> bodyMap = new LinkedHashMap<>();
            bodyMap.put("agetId", config.getAgetId());
            bodyMap.put("custId", appChannelParams.getCustId());
            bodyMap.put("sceneType", payOrderDO.getSceneType() == 2 ? "01" : "02");
            bodyMap.put("orderNo", payOrderDO.getPayOrderNo());
            bodyMap.put("txamt", MerchantUtils.YuanToFen(payOrderDO.getAmount()).toString());
            bodyMap.put("remark", payOrderDO.getSubject());
            bodyMap.put("asyncNotify", channelPayOrderContext.getNotifyUrl());
            bodyMap.put("version", "1.0.0");
            bodyMap.put("timeStamp", DateUtils.getDateString(DatePattern.PURE_DATETIME_PATTERN));
            bodyMap.put("sign", GtzfPayRsaUtil.encrypt(JSONUtil.parseObj(bodyMap), config.getMchPublicKey()));

            String url = domain(channelPayOrderContext.isTest()) + GtzfPayConstant.TRADE_MINI;
            log.info("国通mini统一下单req参数:{}", JsonUtils.toJsonString(bodyMap));
            String response = HttpUtils.post(url, JsonUtils.toJsonString(bodyMap));
            log.info("国通mini统一下单返回参数:{}", response);

            JSONObject rspBody = JsonUtils.parseObj(response);
            if ("000000".equals(rspBody.getStr("code"))) {
                JSONObject respStateInfo = rspBody.getJSONObject("data");
                channelPayOrderContext.setPayDataType("data");
                Map<String,String> payInfo = new HashMap<>();
                payInfo.put("userName", respStateInfo.getStr("appid"));
                payInfo.put("path", respStateInfo.getStr("path"));
                payInfo.put("schemeCode", respStateInfo.getStr("urlScheme"));

                channelPayOrderContext.setPayInfo(JSONUtil.toJsonStr(payInfo));
            } else {
                String respDesc = rspBody.getStr("msg");
                channelPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderContext.setRemark(respDesc);
                } else {
                    channelPayOrderContext.setRemark("国通提交mini统一下单查询返回错误信息为空,错误码为:" + rspBody.getStr("code"));
                }
            }
        } catch (Exception e) {
            log.error("国通提交mini统一下单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderContext.setRemark("国通提交mini统一下单请求失败,失败信息" + e.getMessage());
            channelPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    private String getPayType(PayWayDO payWayDO) {
        PayEnums.SCENE_PAY_TYPE scenePayType = PayEnums.SCENE_PAY_TYPE.from(payWayDO.getSubType());
        PayEnums.PAY_TYPE payType = PayEnums.PAY_TYPE.fromByCode(payWayDO.getType());
        if (Objects.isNull(scenePayType) || Objects.isNull(payType)) return "";
        switch (payType) {
            case WECHAT:
                switch (scenePayType) {
                    case JSAPI:
                    case QR:
                        return "5";
                    case APP:
                    case H5:
                    case MINI_APP:
                        return "8";
                }
        }
        return "";
    }

    @Override
    public void queryChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonQueryChannelPayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void closeChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonCloseChannelPayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void queryChannelClosePayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        commonQueryChannelClosePayOrder(channelPayOrderQueryContext);
    }

    @Override
    public void refundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    @Override
    public void queryRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        commonQueryRefundChannelPayOrder(channelRefundPayOrderContext);
    }

    @Override
    public boolean refundApply(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        return true;
    }

    @Override
    public CommonResult<String> channelOrderCode(ChannelPayOrderContext channelPayOrderContext) {
        return CommonResult.success();
    }

}
